# -*- coding: utf-8 -*-

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from lxml import etree
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import Select
import time
from fake_useragent import UserAgent
import csv


"""
WebDriver 只能在一个页面上对元素识别与定位，对于frame/iframe 表单内嵌页面上的元素无法直接定位
需要通过switch_to.frame()方法将当前定位的主体切换为frame/iframe 表单的内嵌页面中
#切换到表单
driver.switch_to.frame("x-URS-iframe")
打开新的标签页
js=f'window.open("{url}");'
driver.execute_script(js)
------Select------
# 选中这个标签，然后使用Select创建对象
selectTag = Select(driver.find_element_by_name("jumpMenu"))
# 根据索引选择
selectTag.select_by_index(1)
# 根据值选择
selectTag.select_by_value("值")
# 根据可视的文本选择
selectTag.select_by_visible_text("显示值")
# 取消选中所有选项
selectTag.deselect_all()
------Select------
"""

# 初始化
def init_driver(url):
    firefox_options = Options()
    # fire_options.add_argument('--headless') # 无头模式
    firefox_options.add_argument('--disable-gpu')
    firefox_options.set_preference("general.useragent.override", 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36')  # 修改请求头，伪装浏览器型号
    # driver = webdriver.Chrome(chrome_options=chrome_options) # 已经设置PATH环境变量
    # 未在PATH环境变量中设置，需要设置驱动可执行路径
    driver = webdriver.Firefox(executable_path='D:\\webdriver\\geckodriver.exe', options=firefox_options)
    driver.maximize_window()  # 浏览器最大化
    driver.get(url)
    return driver


# 获取页面url
def get_url(drive, search):

    WebDriverWait(driver, 50).until(
        EC.presence_of_element_located((By.NAME, "ApplicationNumber")))
    # 清空search
    driver.find_element_by_name("ApplicationNumber").clear()
    time.sleep(0.5)
    # 设置搜索关键字
    driver.find_element_by_name("ApplicationNumber").send_keys(search)
    time.sleep(0.5)
    # 搜索
    driver.find_element_by_css_selector('[class="doSearchBt btn btn-primary btn-large"]').click()
    time.sleep(2)
    selector = etree.HTML(driver.page_source)
    result = "".join(selector.xpath('//div[@class="search-results"]/div/text()')).replace("\n", "").strip()
    if result == "":
        flag = "是"
    elif result.find("No results") == 0:
        flag = "否"
    # 保存结果
    with open("./XDY_result.csv", 'a+', encoding="utf-8-sig", newline='') as f:
        csv_writer = csv.writer(f)
        csv_writer.writerow([search, flag])

    # 点击-修改搜索按钮
    # driver.find_element_by_xpath('//a[@class="doSearchBt btn btn-primary btn-large"]').click()
    driver.find_element_by_xpath('//nav[@class="searchButtons page-options"]').click()
    time.sleep(1)
    # WebDriverWait(driver, 50).until(
    #         EC.presence_of_element_located((By.NAME, "ApplicationNumber")))




def close_driver(driver):
    driver.quit()

if __name__ == '__main__':
    search_list = []
    line_num = 0
    with open("./XDY.csv", 'r', encoding="utf-8-sig", newline='') as f:
        reader = csv.reader(f)
        for line in reader:
            search_list.append(line[0].strip())

    url = "https://euipo.europa.eu/eSearch/#advanced/trademarks"
    driver = init_driver(url)
    WebDriverWait(driver, 50).until(
        EC.presence_of_element_located((By.NAME, "ApplicationNumber")))
    #
    selectTag = Select(driver.find_element_by_xpath('//select[@class="keyFilter span12"]'))
    selectTag.select_by_index(1)
    selectTag1 = Select(driver.find_elements_by_xpath('//div[@class="criteriaRows"]//select[@class="span12"]')[1])
    selectTag1.select_by_index(1)


    for s in search_list:
        line_num += 1
        print(f"=====line：{line_num}=====search：{s}=============")
        get_url(driver, s)
